﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SoundManager : MonoBehaviour {
	public AudioClip[] audioArray;
	AudioSource audioSource;

	List<AudioSource> audioSourceList;

	AudioSource bgmAudioSource = null;

	public static SoundManager Instance = null;
	void Awake()
	{
		Instance = this;
	}

	// Use this for initialization

	void Start () 
	{

	}

	public void Init()
	{
		audioSource = GetComponent<AudioSource>();
		audioSourceList = new List<AudioSource>();
		audioSourceList.Add(audioSource);
	}
	
	// Update is called once per frame
	void Update () {
		
	}

	public void PlayBGM()
	{
		bgmAudioSource = PlaySoundWithID(5);
		bgmAudioSource.loop = true;
	}

	public void StopBGM()
	{
		bgmAudioSource.Stop();
		bgmAudioSource.loop = false;
	}

	public AudioSource PlaySoundWithID(int id)
	{
		int i = 0;
		for(; i < audioSourceList.Count; i++)
		{
			if(!audioSourceList[i].isPlaying)
			{
				audioSourceList[i].clip = audioArray[id];
				audioSourceList[i].Play();
				return audioSourceList[i];
			}
		}

		if(i == audioSourceList.Count)
		{
			var audioSource = gameObject.AddComponent<AudioSource>();//GameObject.Instantiate(audioSourceList[0]) as AudioSource;
			audioSource.clip = audioArray[id];
			audioSource.Play();
			audioSourceList.Add(audioSource);
			return audioSource;
		}

		return null;
	}
}
